package com.wanyang.controller;


import com.wanyang.core.page.Page;
import com.wanyang.util.ResponseData;
import com.wanyang.util.Status;
import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;

import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.PrintWriter;


/**
 * Description:
 */
public abstract class BaseController {

    protected Logger logger = Logger.getLogger(this.getClass());

    public static String customerBaseDir = "/server/";

    /**
     * 构造函数
     */
    public BaseController() {
    }

    protected ResponseData injectErrorResponse(String errorMsg) {
        ResponseData responseData = new ResponseData();
        responseData.setData(null);
        responseData.setStatus(Status.error);
        responseData.setMsg(errorMsg);
        return responseData;
    }

    protected ResponseData injectSuccessResponse(Object data, String msg) {
        ResponseData responseData = new ResponseData();
        responseData.setData(data);
        responseData.setStatus(Status.success);
        responseData.setMsg(msg);
        return responseData;
    }

    protected void injectResponse(HttpServletResponse response, String info) throws Exception {
        response.setContentType("text/html;charset=UTF-8");
        response.setCharacterEncoding("UTF-8");
        response.setHeader("Cache-Control", "no-cache");
        PrintWriter pw = response.getWriter();
        pw.write(info);
        pw.flush();
        pw.close();
    }

    protected Page initPage(HttpServletRequest request) {
        Page page = new Page();
        String pageString = getParameterWithDefault(request, "10", "1");
        String sizeString = getParameterWithDefault(request, "10", "1");
        if (StringUtils.isNumeric(pageString)) {
            page.setPage(Integer.parseInt(pageString));
            if (StringUtils.isNumeric(sizeString)) {
                page.setLimit(Integer.parseInt(sizeString));
            } else {
                page.setLimit(Integer.parseInt("10"));
            }
        }
        return page;
    }

    private String getParameterWithDefault(HttpServletRequest request, String name, String defaultValue) {
        String paramValue = request.getParameter(name);
        return paramValue != null ? paramValue.trim() : defaultValue;
    }


}
